<template>
  <div class="search-page">
    <!-- 搜索结果标题 -->
    <div class="search-header">
      <h1 class="search-title">{{ orderBy }}的搜索结果：</h1>
      <button class="sort-button" @click="orderBy = '升序'" v-if="orderBy == '综合'">
        按价格升序
      </button>
      <button class="sort-button" @click="orderBy = '降序'" v-if="orderBy == '升序'">
        按价格降序
      </button>
      <button class="sort-button" @click="orderBy = '综合'" v-if="orderBy == '降序'">
        按价格综合
      </button>
    </div>

    <!-- 商品展示区域 -->
    <el-scrollbar max-height="900px">
      <div class="product-grid">
        <GoodsItem class="product-item" v-for="good in goods" :item="good" />
        <el-empty
          v-if="goods.length == 0"
          :image-size="400"
          style="margin: 50px 600px"
          description="暂无商品" />
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { searchGoodsInfo } from '@/api/goods'
import GoodsItem from '@/components/GoodsItem.vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'

const route = useRoute()

const searchName = route.query.searchname || ''

const orderBy = ref('综合')

watch(orderBy, () => {
  goods.value = []
  getAllGoods()
})

const goods = ref([])

// 监听参数变化
watch(
  () => route.query.searchname,
  (newValue, oldValue) => {
    goods.value = []
    getAllGoods(newValue)
  }
)

const getAllGoods = async (value) => {
  const res = (await searchGoodsInfo(value || searchName, orderBy.value)).data
  if (res.code == 505) {
    ElMessage.error(res.msg)
    return
  }
  goods.value = res.data
}

getAllGoods()
</script>

<style scoped>
.search-page {
  max-width: 1600px;
  min-height: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.sort-button {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.sort-button:hover {
  background-color: #0056b3;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  justify-items: center;
}

.product-item {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
}

.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 20px;
}
</style>
